package cn.jinjimi.app.main.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;

import cn.jinjimi.base.util.ToastUtils;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.BundleKey;
import cn.jinjimi.app.controller.UserController;
import cn.jinjimi.app.controller.event.DataEvent;
import cn.jinjimi.app.controller.event.FetchCompanyEvent;
import cn.jinjimi.app.controller.event.UploadProfileEvent;
import cn.jinjimi.app.entity.Company;
import cn.jinjimi.app.main.activity.SetCompanyActivity;
import cn.jinjimi.app.main.adapter.CompanyListAdapter;
import cn.jinjimi.app.main.extend.BaseFragment;
import cn.jinjimi.app.main.widget.biz.CompanyListHeaderView;
import cn.jinjimi.app.main.widget.SideBar;
import cn.jinjimi.app.main.widget.XListView.XListView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by lforxeverc on 16/7/27.
 */
public class CompanyListFragment extends BaseFragment implements CompanyListHeaderView.OnHeaderItemSelectListener, SideBar.OnTouchingLetterChangedListener, XListView.IXListViewListener, AdapterView.OnItemClickListener {
    private LinearLayout llSearch;
    private SideBar sideBar;
    private TextView tvMoveTips;
    private CompanyListHeaderView headerView;
    private XListView mListView;
    private CompanyListAdapter mAdapter;
    int selectType;

    private Company mCompany;

    @Override
    protected int getLayoutResourceId() {
        return R.layout.fragment_company_list;
    }

    @Override
    protected void initial() {
        selectType = getArguments().getInt(SetCompanyActivity.TYPE_KEY, 0);
        String companyName = getArguments().getString(SetCompanyActivity.TYPE_COMPANY, null);
        llSearch = (LinearLayout) findView().findViewById(R.id.ll_header_search);
        mListView = (XListView) findView().findViewById(R.id.lv_company);
        sideBar = (SideBar) findView().findViewById(R.id.layout_sideBar);
        tvMoveTips = (TextView) findView().findViewById(R.id.tv_index);
        headerView = new CompanyListHeaderView(getActivity(), this);
        llSearch.setOnClickListener(this);
        sideBar.setTextView(tvMoveTips);
        sideBar.setOnTouchingLetterChangedListener(this);

        mListView.setTransparentBg();
        mListView.addHeaderView(headerView);
        mListView.setPullLoadEnable(false);
        mListView.setPullRefreshEnable(true);
        mListView.setXListViewListener(this);
        mListView.setOnItemClickListener(this);
        mAdapter = new CompanyListAdapter(getActivity());
        mListView.setAdapter(mAdapter);

        onRefresh();
    }

    public void setCompany() {

    }


    @Override
    public void onResume() {
        super.onResume();
        getActivity().setTitle("选择公司");
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.ll_header_search:
                FragmentManager fm = getActivity().getSupportFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                ft.replace(R.id.fragment_container, CompanySearchFragment.newInstance(mAdapter.getItems(), selectType));
                ft.addToBackStack(null);
                ft.commit();
                break;
        }
    }

    @Override
    public void onHeaderItemSelected(Company company) {
        mCompany = company;
        if (selectType == SetCompanyActivity.TYPE_UPLOAD_COMPANY) {
            setCompany();
        } else {
            returnResult();
        }
    }

    @Override
    public void onTouchingLetterChanged(String s) {


    }

    @Override
    public void onRefresh() {
        UserController.getAllCompanies();
        UserController.getHotCompanies();
    }

    @Override
    public void onLoadMore() {

    }

    private void updateIndexFlag(List<Company> companys) {
        List<String> indexFlag = new ArrayList<String>();
        String[] chars = new String[indexFlag.size()];
        sideBar.setVisibility(View.VISIBLE);
        sideBar.setIndexChars(indexFlag.toArray(chars));
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (mAdapter.getItem(position - mListView.getHeaderViewsCount()) != null) {
            mCompany = mAdapter.getItem(position - mListView.getHeaderViewsCount());
            if (selectType == SetCompanyActivity.TYPE_UPLOAD_COMPANY) {
                setCompany();
            } else {
                returnResult();
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFetchCompanyEvent(FetchCompanyEvent event) {
        ((SetCompanyActivity) getActivity()).hideLoadingIndicator();
        mListView.stopRefresh();
        switch (event.state) {
            case DataEvent.SUCC:
                updateUI(event);
                break;
            case DataEvent.FAIL:
                ToastUtils.toastMessage(getActivity(), (String) event.msg);
                break;
        }

    }

    private void updateUI(FetchCompanyEvent event) {
        List<Company> returnData = event.data.data;
        if (returnData == null || returnData.size() <= 0) {
            return;
        }
        headerView.setAdapter(returnData);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUploadProfileEvent(UploadProfileEvent event) {
        if (getActivity().isFinishing() && !isVisible())
            return;
        ((SetCompanyActivity) getActivity()).hideLoadingIndicator();

        switch (event.state) {
            case DataEvent.SUCC:
                ToastUtils.toastMessage(getActivity(), "修改成功");
                getActivity().finish();
                break;
            case DataEvent.FAIL:
                ToastUtils.toastMessage(getActivity(), "修改失败，请稍后重试");
                break;
        }
    }

    public static CompanyListFragment newInstance(int type, String companyName) {
        CompanyListFragment f = new CompanyListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(SetCompanyActivity.TYPE_KEY, type);
        bundle.putString(SetCompanyActivity.TYPE_COMPANY, companyName);
        f.setArguments(bundle);
        return f;
    }

    private void returnResult() {
        Intent i = getActivity().getIntent();
        i.putExtra(BundleKey.PARAM_COMPANY, mCompany);
        getActivity().setResult(Activity.RESULT_OK, i);
        getActivity().finish();
    }
}
